const fs = require("fs");
const path = require("path");

function getImagesInFolder(folderPath) {
  const images = []; // 存放图片路径的数组
  const catalogue = [];

  function traverseDirectory(dirPath) {
    const files = fs.readdirSync(dirPath);

    for (let file of files) {
      const fullFilePath = path.join(dirPath, file);

      if (fs.statSync(fullFilePath).isDirectory()) {
        traverseDirectory(fullFilePath); // 如果是子目录则递归调用自身处理该子目录
      } else {
        const extname = path.extname(file);
        const imgFormat = [".jpg", ".jpeg", ".png", "BMP", "svg"];

        if (imgFormat.includes(extname)) {
          images.push(fullFilePath); // 将符合条件的图片路径添加到images数组中
        }
      }
    }
  }

  traverseDirectory(folderPath);

  return images;
}

function buildDirectoryTree(rootPath, tree = {}) {  
  // 获取指定路径下的所有文件和目录  
  fs.readdirSync(rootPath).forEach((item) => {  
    const fullPath = path.join(rootPath, item);  
    const stats = fs.statSync(fullPath);  
  
    // 如果是目录，则递归调用  
    if (stats.isDirectory()) {  
      // 为当前目录创建一个子目录对象  
      if (!tree[item]) {  
        tree[item] = {};  
      }  
      // 递归遍历子目录  
      buildDirectoryTree(fullPath, tree[item]);  
    } else if (stats.isFile()) {  
      // 如果是文件，则添加到当前目录的子项中  
      if (!tree[item]) {  
        tree[item] = { size: stats.size };  
      }  
    }  
  });  
  
  return tree;  
}  

try {
  // 文件夹路径
  /** 常用文件夹路径
   * wallPaper壁纸路径 "F:/Program Files/Steam/steamapps/workshop/content"
   *  */
  const folderPath = fs.readFileSync("文件夹路径.txt");
  const images = getImagesInFolder(folderPath?.toString());

  // 将数组转换为JSON字符串
  // const jsonString = JSON.stringify(images);
  // 同步写入JSON文件
  // fs.writeFileSync("images.json", jsonString);
  console.log("Array has been saved to myArray.json");
} catch (err) {
  console.error("An error occurred:", err);
}
